package com.appleyk.security.springmvc.interceptor;

import com.appleyk.security.springmvc.model.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

/**
 * <p>越努力，越幸运</p>
 * 权限拦截器，主要对登录用户访问某一资源的权限做验证
 * @author appleyk
 * @version V.0.1.1
 * @blob https://blog.csdn.net/appleyk
 * @date created on  9:11 下午 2021/1/3
 */
@Component
public class AuthenticateInterceptor implements HandlerInterceptor {

    // 在所有请求处理前，执行
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userName = (String)request.getParameter("userName");
        if(userName == null){
            writeContent("当前用户名为空，请先登录！",response);
        }

        // 否则，拿session,取出当前用户会话信息
        Object data = request.getSession().getAttribute(userName);

        if (data == null){
            writeContent("当前用户未登录，请先登录！",response);
        }

        UserDto userDto = (UserDto) data;
        // 获取session中用户信息中的权限列表
        Set<String> purview = userDto.getPurview();
        // 获取当前请求url，通过url可以知道访问的是哪一个资源
        String requestURI = request.getRequestURI();

        // 如果有访问资源r1的权限的话，拦截器通过验证，返回true
        if (purview.contains("p1") && requestURI.contains("/r/r1")){
            return true;
        }

        // 如果有访问资源r2的权限的话，拦截器通过验证，返回true
        if (purview.contains("p2") && requestURI.contains("/r/r2")){
            return true;
        }

        writeContent("没有权限，拒绝访问！",response);
        return false;
    }

    private void writeContent(String content, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(content);
        writer.close();
    }
}
